package com.example.emailWeb.Socket.SimpleDemo;

import java.io.IOException;
import java.net.Socket;

public class HandleDataBuffer {
    private DataBuffer dataBuffer;
    private Socket socket;
    private SenderDataBuffer senderDataBuffer;

    /**
     * 将新生成的dataBUffer，返回给dataBuffer里面指定的socket
     * @param dataBuffer
     */
    public HandleDataBuffer(DataBuffer dataBuffer) throws IOException {
        this.dataBuffer = dataBuffer;
        dealDataBuffer();
    }

    /**
     * 将新生成的dataBuffer，发给某个Socket
     * @param dataBuffer
     * @param socket
     */
    public HandleDataBuffer(DataBuffer dataBuffer, Socket socket) throws IOException {
        this.dataBuffer = dataBuffer;
        this.socket = socket;
        dealDataBuffer();
    }

    public void dealDataBuffer() throws IOException {

        if(dataBuffer.getFileName()!=null){
            //将该dataBuffer，发送给服务器并设置stop=true。
            DataBuffer dataBuffer0 = new DataBuffer();
            dataBuffer0.setStop(true);
            dataBuffer0.setSocket(socket);
            //发给服务器
            Socket serverSocket= new Socket("localhost",SocketPort.ClientServerPort);
            new SenderDataBuffer(serverSocket,dataBuffer0);
        }
        //一般都是把这个消息修改之后再发给其他人
        if(dataBuffer.isStop()){
            System.out.println("已停下");
            System.out.println(dataBuffer.getMsg());
            return;
        }
        if(dataBuffer.isBack()){
            //将msg，2倍之后返回
            DataBuffer dataBuffer2 = new DataBuffer();
            dataBuffer2.clonePrimaryKey(dataBuffer);
            dataBuffer2.setMsg(dataBuffer.getMsg()+dataBuffer.getMsg());
            senderDataBuffer = new SenderDataBuffer(socket,dataBuffer2);
            return;
        }
        if(dataBuffer.isSendOther()){
            if (dataBuffer.getSocket()!=null){
                senderDataBuffer = new SenderDataBuffer(dataBuffer.getSocket(),dataBuffer);
            }
            return;
        }
    }
}
